<!--
	THIS EXAMPLE WAS DOWNLOADED FROM https://echarts.apache.org/examples/zh/editor.html?c=line-smooth&code=PYBwLglsB2AEC8sDeAoWsAeBBDEDOAXMmurGAJ4gCmRA5AMYCGYVA5sAE7m0A0J6AE2aMiAbVoBZGL1i0AKgFcqM2gHUqAlXIAWClQDEOEFQGVmphdFoBdEgF8-6cjnxFUpMpRqyAbowA2SrT2jrB4VEZUhLCi_MQegsJiABwATAAMPLAAnADMqVnZ6QCMhbkALFnFqUVVubmZsMX56dahHhTUdP4Q0MrtpHgAtsDAYNpEYBxKA-h45EMARsD-RABE0DBUa3F2JLZ2ANxAA
	请注意，该图表不是 Apache ECharts 官方示例，而是由用户代码生成的。请注意鉴别其内容。
-->
<!DOCTYPE html>
<html lang="zh-CN" style="height: 100%">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
</head>
<body style="height: 100%; margin: 0; background: #F1F3FB;">
<div id="container" style="height: 100%"></div>
<script type="text/javascript" src="file:///android_asset/echarts.min.js"></script>
<!-- Uncomment this line if you want to dataTool extension
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts@5.3.3/dist/extension/dataTool.min.js"></script>
-->
<!-- Uncomment this line if you want to use gl extension
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts-gl@2/dist/echarts-gl.min.js"></script>
-->
<!-- Uncomment this line if you want to echarts-stat extension
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts-stat@latest/dist/ecStat.min.js"></script>
-->
<!-- Uncomment this line if you want to use map
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts@4.9.0/map/js/china.js"></script>
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts@4.9.0/map/js/world.js"></script>
-->
<!-- Uncomment these two lines if you want to use bmap extension
<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=YOUR_API_KEY"></script>
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts@5.3.3/dist/extension/bmap.min.js"></script>
-->

<script type="text/javascript">

var option;
// 日期格式化
 function parseTime(time, pattern) {

if (arguments.length === 0 || !time) {
  return null
}
const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
  date = time
} else {
  if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
    time = parseInt(time)
  } else if (typeof time === 'string') {
    // safari不兼容毫秒
    if (time.indexOf('.') > -1) {
      time = time.substring(0, time.indexOf('.'))
    }
    /** 由于后台传入的时间都包含T，因此将T转为一个空格*/
    time = time.replace(new RegExp(/T/gm), ' ')
    time = time.replace(new RegExp(/-/gm), '/')
  }
  if ((typeof time === 'number') && (time.toString().length === 10)) {
    time = time * 1000
  }
  date = new Date(time)
}
const formatObj = {
  y: date.getFullYear(),
  m: date.getMonth() + 1,
  d: date.getDate(),
  h: date.getHours(),
  i: date.getMinutes(),
  s: date.getSeconds(),
  a: date.getDay()
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  let value = formatObj[key]
  // Note: getDay() returns 0 on Sunday
  if (key === 'a') {
    return ['日', '一', '二', '三', '四', '五', '六'][value]
  }
  if (result.length > 0 && value < 10) {
    value = '0' + value
  }
  return value || 0
})
return time_str
}

 function getTimeList(startTime, endTime, type) {
  let span = 0
  let timeList = []
  if (type == 'month') { // 获取月的时间列表
    startTime = parseTime(startTime).slice(0, 7) + '-01 00:00:00'
    endTime = parseTime(endTime).slice(0, 10) + ' 23:59:59'
    startTime = new Date(startTime).valueOf()
    endTime = new Date(endTime).valueOf()
    for (; startTime < endTime;) {
      timeList.push(parseTime(startTime))
      startTime = new Date(startTime).setMonth(new Date(startTime).getMonth() + 1)
      startTime = new Date(startTime).valueOf()
    }
  } else if (type == 'week') { // 获取周的时间列表
    startTime = parseTime(startTime).slice(0, 10) + ' 00:00:00'
    endTime = parseTime(endTime).slice(0, 10) + ' 23:59:59'
    startTime = new Date(startTime).valueOf()
    endTime = new Date(endTime).valueOf()
    for (; startTime < endTime; startTime += 1000 * 3600 * 24 * 7) {
      timeList.push(moment(startTime).startOf('isoWeek').format('yyyy-WW'))
    }
  } else if (type == 'day') { // 获取天的时间列表
    startTime = parseTime(startTime).slice(0, 10) + ' 00:00:00'
    endTime = parseTime(endTime).slice(0, 10) + ' 23:59:59'
    span = 1000 * 3600 * 24
  } else if (type == 'hour') { // 获取小时的时间列表
    span = 1000 * 3600
  } else if (type == 'minute') { // 获取分钟的时间列表
    span = 1000 * 60
  }
  if (type == 'day' || type == 'hour' || type == 'minute') {
    startTime = new Date(startTime).valueOf()
    endTime = new Date(endTime).valueOf()
    for (; startTime < endTime; startTime += span) {
      timeList.push(parseTime(startTime))
    }
  }
  return timeList
}

function getFontSize(time){
  return time*1.2
}
  function data(msg) {
    const  colors = [
       '#0088FF',
        '#13CE66',
        '#FF6666',
        '#FF9C00',
        '#FFCC00',
        '#FF1111',
        '#CCCC33',
        '#00E0D3',
        '#00C0CC',
        '#0095C6',
        '#66CCFF',
        '#0044FF',
        '#3300CC',
        '#CC0033',
        '#CC33CC',
        '#FFAAAA',
      ];
      const   hourItem =  [
        {
          name: '平均值',
          key: 'avgVal',
        },
        {
          name: '最大值',
          key: 'maxVal',
        },
        {
          name: '最小值',
          key: 'minVal',
        }
      ];

   const envDict = {
  'xkIndex': {
    name: '小科指数',
    unit: '',
  },
  'vent': {
    name: '通风量',
    unit: 'k·m³/h',

  },
  'temp': {
    name: '温度',
    unit: '℃',
    typeId: 1,
    itemList: [
      {name: '平均温度', key: 'curVal'},
      {name: '目标温度', key: 'tarVal'},
      {name: '高温报警', key: 'hVal'},
      {name: '低温报警', key: 'lVal'},
      {name: '体感温度', key: 'thwVal'},
      {name: '温度1', key: 'sensor1', type: 'temp', subId: 0},
      {name: '温度2', key: 'sensor2', type: 'temp', subId: 1},
      {name: '温度3', key: 'sensor3', type: 'temp', subId: 2},
      {name: '温度4', key: 'sensor4', type: 'temp', subId: 3},
      {name: '温度5', key: 'sensor5', type: 'temp', subId: 4},
      {name: '温度6', key: 'sensor6', type: 'temp', subId: 5},
      {name: '温度7', key: 'sensor7', type: 'temp', subId: 6},
      {name: '温度8', key: 'sensor8', type: 'temp', subId: 7},
      {name: '温度9', key: 'sensor9', type: 'temp', subId: 8},
      {name: '温度10', key: 'sensor10', type: 'temp', subId: 9},
      {name: '温度11', key: 'sensor11', type: 'temp', subId: 10},
      {name: '温度12', key: 'sensor12', type: 'temp', subId: 11},
      {name: '温度13', key: 'sensor13', type: 'temp', subId: 12},
      {name: '温度14', key: 'sensor14', type: 'temp', subId: 13},
      {name: '温度15', key: 'sensor15', type: 'temp', subId: 14},
      {name: '温度16', key: 'sensor16', type: 'temp', subId: 15},
      {name: '室外温度', key: 'outVal'},
      {name: '气候值', key: 'cityTemp'},
    ]
  },
  'humi': {
    name: '湿度',
    unit: '%',
    typeId: 2,
    itemList: [
      {name: '平均湿度', key: 'curVal'},
      {name: '目标湿度', key: 'tarVal'},
      {name: '高湿报警值', key: 'hVal'},
      {name: '低湿报警值', key: 'lVal'},
      {name: '湿度1', key: 'sensor1', type: 'humi', subId: 0},
      {name: '湿度2', key: 'sensor2', type: 'humi', subId: 1},
      {name: '湿度3', key: 'sensor3', type: 'humi', subId: 2},
      {name: '湿度4', key: 'sensor4', type: 'humi', subId: 3},
    ]
  },
  'co2': {
    name: 'CO₂',
    unit: 'ppm',
    typeId: 3,
    itemList: [
      {name: '平均CO₂', key: 'curVal'},
      {name: '目标CO₂', key: 'tarVal'},
      {name: '高CO₂报警值', key: 'hVal'},
      {name: '低CO₂报警值', key: 'lVal'},
      {name: 'CO₂1', key: 'sensor1', type: 'co2', subId: 0},
      {name: 'CO₂2', key: 'sensor2', type: 'co2', subId: 1},
      {name: 'CO₂3', key: 'sensor3', type: 'co2', subId: 2},
      {name: 'CO₂4', key: 'sensor4', type: 'co2', subId: 3},
    ]
  },
  'nh3': {
    name: 'NH₃',
    unit: 'ppm',
    typeId: 4,
    itemList: [
      {name: '平均NH₃', key: 'curVal'},
      {name: '目标NH₃', key: 'tarVal'},
      {name: '高NH₃报警值', key: 'hVal'},
      {name: '低NH₃报警值', key: 'lVal'},
      {name: 'NH₃1', key: 'sensor1', type: 'nh3', subId: 0},
      {name: 'NH₃2', key: 'sensor2', type: 'nh3', subId: 1},
      {name: 'NH₃3', key: 'sensor3', type: 'nh3', subId: 2},
      {name: 'NH₃4', key: 'sensor4', type: 'nh3', subId: 3},
    ]
  },
  'h2s': {
    name: 'H₂S',
    unit: 'ppm',
    typeId: 5,
    itemList: [
      {name: '平均H₂S', key: 'curVal'},
      {name: '目标H₂S', key: 'tarVal'},
      {name: '高H₂S报警值', key: 'hVal'},
      {name: '低H₂S报警值', key: 'lVal'},
      {name: 'H₂S1', key: 'sensor1', type: 'h2s', subId: 0},
      {name: 'H₂S2', key: 'sensor2', type: 'h2s', subId: 1},
      {name: 'H₂S3', key: 'sensor3', type: 'h2s', subId: 2},
      {name: 'H₂S4', key: 'sensor4', type: 'h2s', subId: 3},
    ]
  },
  'pm25': {
    name: 'PM2.5',
    unit: '',
    typeId: 12
  },
  'pm10': {
    name: 'PM10',
    unit: '',
    typeId: 13
  },
  'np': {
    name: '静压',
    unit: 'Pa',
    typeId: 6,
    itemList: [
      {name: '平均静压', key: 'curVal'},
      {name: '目标静压', key: 'tarVal'},
      {name: '高静压报警值', key: 'hVal'},
      {name: '低静压报警值', key: 'lVal'},
    ]
  },
  'ium': {
    name: '光照',
    unit: 'Lx',
    typeId: 11
  },
  'ph': {
    name: 'ph',
    unit: '',
    typeId: 9
  },
  'vend': {
    name: '通风量',
    unit: 'k·m³/h',
    typeId: 100,
    itemList: [
      {name: '当前通风量', key: 'curVal'},
      {name: '当前级别', key: 'gradeVal'},
    ]
  },
  'vendGrade': {
    name: '通风级别',
    unit: 'Lv',
    typeId: 101,
    itemList: [
      {name: '当前级别', key: 'curVal'},
    ]
  },
  'velocity': {
    name: '风速',
    unit: 'm/s',
    typeId: 7,
    itemList: [
      {name: '平均风速', key: 'curVal'},
      {name: '目标风速', key: 'tarVal'},
      {name: '高风速报警值', key: 'hVal'},
      {name: '低风速报警值', key: 'lVal'},
      {name: '风速1', key: 'sensor1', type: 'velocity', subId: 0},
      {name: '风速2', key: 'sensor2', type: 'velocity', subId: 1},
      {name: '风速3', key: 'sensor3', type: 'velocity', subId: 2},
      {name: '风速4', key: 'sensor4', type: 'velocity', subId: 3},
    ]
  },
  'thw': {
    name: '体感温度',
    unit: '℃',
    typeId: 10
  },
  'outTemp': {
    name: '室外温度',
    unit: '℃',
    typeId: 8
  },
  'ch4': {
    name: 'CH₄',
    unit: '%VOL',
    typeId: 15
  }
}
    var dom = document.getElementById("container");
    var myChart = echarts.init(dom);
    var option;
    let dataAll = JSON.parse(msg);
    let chartData =  dataAll.chartData
    let  tempData = dataAll.tempData
    let  type =  dataAll.type
    let   isHour =  dataAll.isHour
    let isWS =  { type: Boolean, default: false}
      let xData = []
      let series = []
      let dataZoom=[]
      let showItem = {}
      let dataMap = {}
      let tempMap = {}
      let timeFormat = '{m}-{d} {h}:{i}'
      if (isHour) {
        timeFormat = '{m}-{d} {h}'
      }
      xData = chartData.sort((a, b) => new Date(a.time).valueOf() - new Date(b.time).valueOf()).map(item => parseTime(item.time))
      if (xData.length > 0) {
        if (isHour) {
          xData = getTimeList(xData[0],xData[xData.length-1],'hour').map(item => parseTime(item, timeFormat))
        }else {
          xData = xData.map(item => parseTime(item, timeFormat))
        }
      }
      chartData.forEach(ele => {
        dataMap[parseTime(ele.time, timeFormat)] = ele
      })
      tempData.forEach(ele => {
        tempMap[parseTime(ele.time, timeFormat)] = ele
      })
      if (isHour) {
        hourItem.forEach(ele => {
          let name = ele.name
          series.push({
            name: envDict[type]?.name + name,
            yAxisIndex: 0,
            type: 'line',
            showSymbol: false,
            // data: chartData.map(item => [that.parseTime(item.time, timeFormat), item[ele.key]] || null),
            data: xData.map(item => [item, dataMap[item]?.[ele.key]] || null).filter(val => val[1]) || [],
          })
        })
        if (type != 'temp' && tempData.length > 0) {
          series.push({
            name: '平均温度',
            color: '#FFAA00',
            yAxisIndex: 1,
            type: 'line',
            showSymbol: false,
            data: xData.map(item => [item, tempMap[item]?.['avgVal']] || null).filter(val => val[1]) || [],
          })
        }
      }else {
        envDict[type]?.itemList.filter(val => {
          if (isWS) {
            return val.key.indexOf('sensor') == -1
          }else {
            return true
          }
        }).forEach(ele => {
          if (chartData[chartData.length -1]?.[ele.key]) {
            let name = ele.name
            // if (ele.type) {
            //   name = customSensor(houseId, ele.type, ele.subId)
            // }
            series.push({
              name: name,
              yAxisIndex: ele.key == 'gradeVal' ? 1 : 0,
              type: 'line',
              showSymbol: false,
              data: xData.map(item => [item, dataMap[item]?.[ele.key]] || null),
            })
          }
        })
        if (type != 'temp' && type != 'vend' && tempData.length > 0) {
          series.push({
            name: '平均温度',
            color: '#FFAA00',
            yAxisIndex: 1,
            type: 'line',
            showSymbol: false,
            data: xData.map(item => [item, tempMap[item]?.['curVal']] || null),
            // data: tempData.map(item => [that.parseTime(item.time, timeFormat), item['curVal']] || '--'),
          })
        }
      }
      series.forEach(ele => {
        if (ele.name.indexOf('平均') != -1 || ele.name.indexOf('当前') != -1) {
          ele.color = '#0066ff'
        }
        if (ele.name.indexOf('目标') != -1) {
          ele.color = '#33cc66'
        }
        if (ele.name.indexOf('高') != -1 || ele.name.indexOf('最大值') != -1) {
          ele.color = '#ff2222'
        }
        if (ele.name.indexOf('低') != -1 || ele.name.indexOf('最小值') != -1) {
          ele.color = '#00ccff'
        }
        if (ele.name.indexOf('平均温度') != -1) {
          ele.color = '#FFAA00'
        }
        if (type == 'vend' && ele.name == '当前级别') {
          ele.color = '#FFAA00'
        }
        ele['lineStyle'] = {
          width: 2
        }
      })
    //  if (!isHour){
        // dataZoom = [
        //   {
        //     show: true,
        //     realtime: true,
        //     start: 0,
        //     end: 100,
        //     xAxisIndex: [0, 1]
        //   },
        //   {
        //     type: 'inside',
        //     realtime: true,
        //     start: 0,
        //     end: 100,
        //     xAxisIndex: [0, 1]
        //   }
        // ]
     // }
      if (!isHour) {
        if (type == 'temp') {
          series.forEach(el => {
            if (el.name == "平均温度" || el.name == "目标温度") {
              showItem[el.name] = true
            } else {
              showItem[el.name] = false
            }
            if (el.name == "平均温度" ) {
              el['markPoint'] = {
                symbol: 'roundRect',
                symbolSize: [getFontSize(40), getFontSize(20)], // 容器大小
                symbolOffset: [0, 0], //位置偏移
                data: [{type: 'max'}, {type: 'min'}],
                label:{ fontSize: getFontSize(18)},
              }
            }
            el['smooth'] = false
          })
        } else {
          series.forEach(el => {
            if (el.name == "平均温度") {
              showItem[el.name] = true
            } else if ((el.name.indexOf('平均') >= 0 || el.name.indexOf('目标') >= 0) && el.name != "目标温度" || el.name =="当前级别" || el.name == "当前通风量") {
              showItem[el.name] = true
            } else {
              showItem[el.name] = false
            }
            if (el.name.indexOf('平均') >= 0 || el.name == "平均温度" ) {
              el['markPoint'] = {
                symbol: 'roundRect',
                symbolSize: [getFontSize(40), getFontSize(20)], // 容器大小
                symbolOffset: [0, 0], //位置偏移
                data: [{type: 'max'}, {type: 'min'}],
                label:{ fontSize: getFontSize(18)},
              }
            }
            el['smooth'] = false
          })
        }
      }

       option = {
        backgroundColor: '#F1F3FB',
        color: colors,
        // dataZoom: dataZoom,
        tooltip: {
          backgroundColor: 'rgba(255,255,255,0.5)',
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              fontSize: getFontSize(18)
            }
          },
          textStyle:{ fontSize: getFontSize(18)},
          formatter: function (params) {
            let list = []
            let listItem = ''
            list[0] = `<span style="display:inline-block;">
                    ${params[0].axisValue}</span> `
            if (dataMap[params[0].axisValue]?.dayAge) {
              list[0] += `(${dataMap[params[0].axisValue]?.dayAge}${'日龄'})`
            }
            for (var i = 0; i < params.length; i++) {
              if (params[i].seriesName !='时间') {

                let unit = envDict[type].unit

                if (params[i].seriesName.indexOf('温') != -1) {
                  unit = '℃'
                }
                if (params[i].seriesName=='平均通风量'){
                  unit = 'k·m³'
                }
                if (params[i].seriesName=='当前级别'){
                  unit = 'Lv'
                }
                list.push(
                    '<i style="display: inline-block;width: 10px;height: 10px;background: ' +
                    params[i].color +
                    ';margin-right: 5px;border-radius: 50%;}"></i><span >' +
                    params[i].seriesName +
                    '</span>：' +
                   ( unit == 'Lv' ? (unit + (params[i].data[1] ?? '--')) : ((params[i].data[1] ?? '--') + unit))
                )
              }
            }
            listItem = list.join('<br>')
            return '<div style="padding-right: 10px;font-size: '+getFontSize()+'">' + listItem + '</div>'
          },
          position: function (point, params, dom, rect, size) {
            var x = 0;
            var y = 0;
            var pointX = point[0];
            var pointY = point[1];
            var boxWidth = size.contentSize[0];
            var boxHeight = size.contentSize[1];
            if (boxWidth > pointX) {
              x = 5;
            } else { // 左边放的下
              x = pointX - boxWidth;
            }
            if (boxHeight > pointY) {
              y = 5;
            } else { // 上边放得下
              y = pointY - boxHeight;
            }
            return [x, y];
          }
        },
        legend: {

          icon: 'circle',
          right: '40',
          top: '0',
          selected: showItem,
          textStyle: {
            fontSize: getFontSize(18)
          }
        },
        grid: {
          left: type == 'co2'?getFontSize(60) :getFontSize(50),
          right: getFontSize(50),
          top: getFontSize(50),
        bottom:getFontSize(70),
        },
        xAxis: [
          {
            type: 'category',
            data: xData,
            boundaryGap: false,
            axisLine: {
              show: true, //隐藏X轴轴线
            },
            axisLabel: {
              margin: 30,
              show: true,
              rotate: 30,
              align: 'center',
              fontSize: getFontSize(14)
            },
            axisTick: {
              show: false,
            },
            splitLine: {
              show: false,
            },
            splitArea: {show: false}, //去除网格区域
          },
        ],
        yAxis: [
          {
            scale: true,
            type: 'value',
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              show: true,
              fontSize: getFontSize(18)
            },
            splitLine: {
              show: true,
            },
            splitArea: {show: false}, //去除网格区域
          },
          {
            scale: true,
            type: 'value',
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              show: true,
              fontSize: getFontSize(18)
            },
            splitLine: {
              show: true,
            },
            splitArea: {show: false}, //去除网格区域
          }
        ],
        series: series
      }

      option.yAxis[0]['min'] = function (value) {
        let min = parseInt(value.min - 1)
        return Math.floor(min)
      }
      option.yAxis[0]['max'] = function (value) {
        return parseInt(value.max * 1 + 1)
      }

      option.yAxis[1]['min'] = function (value) {
        let min = parseInt(value.min - 1)
        return Math.floor(min)
      }
      option.yAxis[1]['max'] = function (value) {
        return parseInt(value.max * 1 + 1)
      }

    if (option && typeof option === 'object') {
      myChart.setOption(option)
      myChart.getZr().on('mouseup', params => {
        myChart.dispatchAction({
          type: 'hideTip'
        })
      })
    }


}


</script>
</body>
</html>